package com.gx.smart.building.ui.message

import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import com.blankj.utilcode.util.TimeUtils
import com.gx.smart.base.BaseMVVMRefreshActivity
import com.gx.smart.building.R
import com.gx.smart.building.databinding.ActivityMessageDetailBinding
import com.gx.smart.building.ui.message.event.ItemMessageEvent
import com.gx.smart.building.ui.message.viewmodel.MessageViewModel
import com.gx.smart.lib.http.api.response.Message
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MessageDetailActivity : BaseMVVMRefreshActivity<MessageViewModel>() {
    private lateinit var viewBinding: ActivityMessageDetailBinding
    private lateinit var item: Message
    private var mWebView: WebView? = null
    override fun onBindViewModel(): Class<MessageViewModel> = MessageViewModel::class.java

    override fun onBindLayout(): Int = R.layout.activity_message_detail

    override fun getToolbarTitle(): String = "消息详情"

    override fun initContentView(root: ViewGroup) {
        viewBinding = ActivityMessageDetailBinding.inflate(layoutInflater, root, true)
        mWebView = WebView(this)
        mWebView?.overScrollMode = View.OVER_SCROLL_NEVER
        mWebView?.isVerticalScrollBarEnabled = false
        viewBinding.container.addView(
            mWebView, FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            )
        )
    }

    override fun initView() {
        registerEventBus()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
        // activity onDestroy时
        if (mWebView != null && mWebView?.parent != null) {
            (mWebView?.parent as ViewGroup).removeView(mWebView)
            mWebView?.destroy()
            mWebView = null
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun messageEvent(event: ItemMessageEvent) {
        item = event.item
    }

    override fun initData() {
        viewBinding.title.text = item.title
        viewBinding.createTime.text =
            TimeUtils.millis2String(item.createTime.toLong(), "yyyy-MM-dd HH:mm:ss")
        mWebView?.loadDataWithBaseURL(
            "about:blank",
            item.content,
            "text/html",
            "utf-8",
            ""
        )
        viewModel.messageRecordRead(item.id)
    }
}